package com.tedu.egweibo3.base.exception;

import com.tedu.egweibo3.base.response.JsonResult;
import com.tedu.egweibo3.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String[] message = ex.getFieldError().getDefaultMessage().split(":", 1);
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }
    @ExceptionHandler
    public JsonResult deHandleRuntimeException(NullPointerException ex){
        String message = ex.getMessage();
        return new JsonResult(StatusCode.NOT_LOGIN,message);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String message = ex.getMessage().substring(ex.getMessage().indexOf(":"));
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }
}
